/*
PearReview - The peer review assistant.
Copyright (C) 2009  Dimitrij Pankratz, Anton Musichin
http://www.pearreview.com, info@pearreview.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package com.pearreview.util.review;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;

public class IdLinkedList<E extends IdItem> 
		extends LinkedList<E> implements IdList<E> {
	
	private static final long serialVersionUID = 2851921601633964697L;
	
	public IdLinkedList() {
		
	}
	
	public IdLinkedList(Collection<? extends E> c) {
		super(c);
	}

	@Override
	public IdList<E> getWithId(String id) {
		IdList<E> list = new IdLinkedList<E>();
		
		Iterator<E> iter = this.iterator();
		
		E item;
		while(iter.hasNext()) {
			item = iter.next();
			if(item.getId().equals(id)) {
				list.add(item);
			}
		}
		
		return list;
	}

	@Override
	public boolean hasId(String id) {
		Iterator<E> iter = this.iterator();
		
		while(iter.hasNext()) {
			if(iter.next().getId().equals(id)) {
				return true;
			}
		}
		
		return false;
	}

	@Override
	public void regenerateIds() {
		for(int i = size() - 1 ; i >= 0 ; i--) {
			this.get(i).setId(String.valueOf(i + 1));
		}
	}
	
	@Override
	public boolean hasDoubleIds() {
		IdLinkedList<E> set = new IdLinkedList<E>();
		Iterator<E> iter = this.iterator();
		
		while(iter.hasNext()) {
			if(!set.hasId(iter.next().getId())) {
				set.add(iter.next());
			} else {
				return true;
			}
		}
		
		return false;
	}
}
